<template>
  <div class="order-container">
    <!-- 店铺信息 -->
    <view style="padding: 20rpx; background-color: #fff">
      <view class="method-tabs">
        <view
          class="method-tab"
          :class="{ active: singleObj.userType === 1 }"
          @tap="selectMethod(1)"
        >
          业主
        </view>
        <view
          class="method-tab"
          :class="{ active: singleObj.userType === 2 }"
          @tap="selectMethod(2)"
        >
          师傅
        </view>
      </view>
      <view class="choose-user">
        <view style="display: flex; align-items: center">
          <div class="choose-user-label">客户名称：</div>
          <input
            v-if="!singleObj.c_user_id"
            type="text"
            class="choose-input"
            placeholder="请输入客户名称"
            v-model="singleObj.c_user_name"
          />
          <view v-else class="choose-user-name">
            <span>{{ singleObj.c_user_name }}</span>
            <span class="choose-user-name-close" @click="clearUser">×</span>
          </view>
        </view>
        <image
          @click="toChooseUser"
          class="choose-icon"
          mode="fill"
          src="https://cphimg.leyoo888.com/dev/upload/supplier/2025-07-24/1753352070743.png?x-oss-process=image/resize,w_200,h_200"
        ></image>
      </view>
    </view>
    <!-- 客户信息 -->
    <div class="customer-info" @click="switchAddress">
      <div class="customer-row">
        <div class="customer-avatar">
          <image
            src="https://cphimg.leyoo888.com/dev/upload/supplier/2025-05-04/1746344971744.png"
            class="avatar-img"
          >
          </image>
        </div>
        <div class="customer-data">
          <div class="customer-name">
            <span>{{ singleObj.current_address.consignee }}</span>
            <span class="mgl-40">{{ singleObj.current_address.mobile }}</span>
          </div>
          <div class="customer-address">
            {{ singleObj.current_address.address }}
          </div>
        </div>
        <div class="address-arrow">
          <text class="gui-icons arrow-icon">&#xe601;</text>
        </div>
      </div>
    </div>

    <!-- 商品列表 -->
    <div
      class="product-list"
      v-for="(item, index) in singleObj.detail"
      :key="index"
    >
      <div class="product-item">
        <div class="product-required">*</div>
        <SelectGoods
          style="width: 100%"
          v-model="item.goods_id"
          label="商品"
          :options="item.selectOptions.goodsList"
          placeholder="请选择商品"
          :title="`请先选用户再选择商品`"
          @changeGoods="changeGoods(item, index)"
          @loadMore="loadMoreGoods(index)"
        />
      </div>

      <div class="product-item">
        <CascaderGoods
          label="规格"
          required
          placeholder="请选择商品规格"
          :title="`请先选商品再选择规格`"
          :options="item.selectOptions.goodsSpecList"
          v-model="item.sku_id"
          @change="changeSku($event, item, index)"
          style="flex: 1"
        />
      </div>

      <div class="product-item">
        <div class="product-required">*</div>
        <div class="product-label">数量</div>
        <div class="quantity-control">
          <div class="quantity-minus" @click="decreaseQuantity(item)">-</div>
          <!-- <input
            type="number"
            class="quantity-input"
            v-model="item.quantity"
            @change="changeQuantity(item)"
          /> -->
          <NumberInput
              v-model="item.quantity"
              :min="1"
              :max="999"
              class="quantity-input"
              @change="changeQuantity(item)"
            />
          <div class="quantity-plus" @click="increaseQuantity(item)">+</div>
        </div>
      </div>

      <div class="product-item no-required">
        <div class="product-label">备注</div>
        <input
          type="text"
          class="remark-input"
          placeholder="请输入备注内容"
          v-model="item.remark"
        />
      </div>

      <div class="price-info no-required">
        <div class="price-label">单价</div>
        <div class="price-value">
          ¥
         <input type="dight" v-model="item.price" style="width: 200rpx" @change="changePrice(item)"></input>
        </div>
        <div class="total-price">总价: ¥{{ item.total_price }}</div>
      </div>

      <div class="action-buttons">
        <div class="add-button" @click="increaseAddedQuantity(index, item)">
          <gui-image
            src="https://cphimg.leyoo888.com/dev/upload/supplier/2025-05-05/1746427166764.png"
            :width="60"
            :height="60"
          />
          <text class="add-text">添加</text>
        </div>
        <div
          class="add-button"
          v-if="singleObj.detail.length > 1"
          @click="decreaseAddedQuantity(index)"
        >
          <gui-image
            src="https://cphimg.leyoo888.com/dev/upload/supplier/2025-05-05/1746427171920.png"
            :width="60"
            :height="60"
          />
          <text class="add-text">删除</text>
        </div>
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div class="footer">
      <div class="total-section">
        合计: <text class="total-amount">¥{{ totalPrice }}</text>
        <text class="tax-info">(不含运费)</text>
      </div>
      <div class="submit-button" @click="submit">提交</div>
    </div>

    <!-- 地址填写弹窗 -->
    <AddressDialog
      v-model:show="showAddressDialog"
      @confirm="handleAddressConfirm"
    />
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
import {
  getGoodsListForc as getGoodsList,
  getGoodsSpecListForc as getGoodsSpecList,
  proxySetOrderForc,
} from "@/apiShop/order";
import { getUserInfo } from "@/apiShop/mine.js";
import SelectGoods from "@/component/goods/selectGoods.vue";
import { bc, showToast } from "@/utils/helper";
import cloneDeep from "lodash.clonedeep";
import CascaderGoods from "@/component/goods/cascaderGoods.vue";
import AddressDialog from "./component/addressDialog.vue";
import NumberInput from "@/component/numberInput/index.vue";
// 商品数量
const goodsObj = ref({
  sku_id: undefined,
  goods_id: undefined,
  goods_spec_value_name: undefined,
  goods_spec_name: undefined,
  goods_value_name: undefined,
  quantity: 1,
  remark: "",
  price: 0,
  total_price: 0,
  selectOptions: {
    goodsList: [],
    goodsSpecList: [],
    goodsPage: {
      page: 1,
      limit: 99,
    },
  },
});
const singleObj = ref({
  userType: 1,
  c_user_id: undefined,
  c_user_name: "",
  current_address: {
    consignee: "请点击选择地址",
    address: "",
    mobile: "",
    id: undefined,
  },
  user_remark: "",
  detail: [cloneDeep(goodsObj.value)],
});

const totalPrice = computed(() => {
  return singleObj.value.detail.reduce((total, item) => {
    return bc(`${total}+${item.total_price}`);
  }, 0);
});

// 增加数量
const increaseQuantity = (item) => {
  item.quantity += 1;
  item.total_price = bc(`${item.price}*${item.quantity}`);
};
const changeQuantity = (item) => {
  item.quantity = isNaN(Number(item.quantity)) ? 1 : Number(item.quantity);
  item.total_price = bc(`${item.price}*${item.quantity}`);
};
// 减少数量
const decreaseQuantity = (item) => {
  if (item.quantity > 1) {
    item.quantity -= 1;
    item.total_price = bc(`${item.price}*${item.quantity}`);
  }
};

// 增加已添加商品数量
const increaseAddedQuantity = async (index, item) => {
  singleObj.value.detail.splice(index, 0, {
    sku_id: undefined,
    goods_id: item.goods_id,
    goods_spec_value_name: undefined,
    goods_spec_name: undefined,
    goods_value_name: undefined,
    quantity: 1,
    remark: "",
    price: 0,
    total_price: 0,
    selectOptions: {
      goodsList: [],
      goodsSpecList: [],
      goodsPage: {
        page: 1,
        limit: 99,
      },
    },
  });
  await getGoodsListData(index);
  if (item.goods_id) {
    await getGoodsSpecListData(item.goods_id, index);
  }
};

// 减少已添加商品数量
const decreaseAddedQuantity = (index) => {
  singleObj.value.detail.splice(index, 1);
};

const showAddressDialog = ref(false);

const switchAddress = () => {
  if (!singleObj.value.c_user_id) {
    // 如果没有选择用户，显示地址弹窗
    showAddressDialog.value = true;
  } else {
    // 如果已选择用户，则跳转到地址列表
    uni.navigateTo({
      url: `/pagesShop/address/storeAddresslist?is_proxy=1&c_user_id=${singleObj.value.c_user_id}`,
    });
  }
};

// 处理地址弹窗确认事件
const handleAddressConfirm = (address) => {
  singleObj.value.current_address = { ...address, id: address.id };
};

const loadMoreGoods = (index) => {
  singleObj.value.detail[index].selectOptions.goodsPage.limit += 99;
  getGoodsListData(index);
};
// 获取商品列表
const getGoodsListData = async (index) => {
  const res = await getGoodsList({
    ...singleObj.value.detail[index].selectOptions.goodsPage,
    user_id: singleObj.value.c_user_id,
    status: 2,
  });
  singleObj.value.detail[index].selectOptions.goodsList = res.data.map(
    (item) => ({
      id: item.id,
      goods_name: item.goods_name,
      goods_image: item.cover,
    })
  );
  // 清空当前行sku规格列表
  singleObj.value.detail[index].selectOptions.goodsSpecList = [];
  singleObj.value.detail[index].selectOptions.sku_id = undefined;
  singleObj.value.detail[index].selectOptions.goods_id = undefined;
};
// 获取商品规格列表
const getGoodsSpecListData = async (id, index) => {
  const res = await getGoodsSpecList({
    shop_goods_id: id,
    user_id: singleObj.value.c_user_id,
    tree: 1,
  });
  // 处理数据跟采购单一样
  res.forEach((item) => {
    if(item.children){
      item.children.forEach((itChild) => {
      itChild.data.discount_price = itChild.data.sales_price;
      itChild.data.factory_price =
        itChild.data.y_sales_price || itChild.data.sales_price;
    });
    }
    else{
      item.data.discount_price = item.data.sales_price;
      item.data.factory_price =
        item.data.y_sales_price || item.data.sales_price;
    }
  });
  singleObj.value.detail[index].selectOptions.goodsSpecList = res;
};

const changeGoods = (item, index) => {
  getGoodsSpecListData(item.goods_id, index);
  Object.assign(
    item,
    cloneDeep({
      ...goodsObj.value,
      goods_id: item.goods_id,
      goods_spec_value_name: item.goods_spec_value_name,
      goods_spec_name: item.goods_spec_name,
      goods_value_name: item.goods_value_name,
      selectOptions: {
        goodsList: item.selectOptions.goodsList || [],
        goodsSpecList: [],
        goodsPage: {
          page: 1,
          limit: 99,
        },
      },
    })
  );
};

const changeSku = (event, item, index) => {
  item.price = event.discount_price;
  item.total_price = bc(`${event.discount_price} *${item.quantity}`);
  item.goods_spec_name = event.goods_spec_name.join("??");
  item.goods_value_name = event.goods_spec_value_name.join("??");
  let str = "";
  event.goods_spec_name.forEach((item, indexSpe) => {
    str += item + "：" + event.goods_spec_value_name[indexSpe] + " ";
  });
  item.goods_spec_value_name = str;
};

const checkSubmit = () => {
  if (!singleObj.value.current_address?.id) {
    uni.showToast({ title: "请选择收货地址", icon: "none" });
    return false;
  }
  if (!singleObj.value.c_user_name) {
    uni.showToast({ title: "请填写用户名", icon: "none" });
    return false;
  }
  return true;
};

const submit = async () => {
  if (!checkSubmit()) return;
  let res;
  if (singleObj.value.c_user_id) {
    res = await proxySetOrderForc({
      c_user_id: singleObj.value.c_user_id,
      order: [
        // 后端要求的格式
        {
          shop_id: userShopId.value, // 店铺id
          address_id: singleObj.value.current_address.id,
          user_remark: singleObj.value.user_remark || "",
          detail: singleObj.value.detail.map((item) => ({
            goods_id: item.goods_id,
            sku_id: item.sku_id,
            quantity: item.quantity,
            goods_spec_value_name: item.goods_spec_value_name,
            goods_spec_name: item.goods_spec_name,
            goods_value_name: item.goods_value_name,
            price: item.price,
            remark: item.remark,
          })),
        },
      ],
    });
  } else {
    // 后面会删掉 临时匿名用户通道
    res = await proxySetOrderForc({
      c_user_id: 0,
      order: [
        // 后端要求的格式
        {
          ...singleObj.value.current_address,
          username: singleObj.value.c_user_name,
          shop_id: userShopId.value, // 店铺id
          address_id: 0,
          user_remark: singleObj.value.user_remark || "",
          detail: singleObj.value.detail.map((item) => ({
            goods_id: item.goods_id,
            sku_id: item.sku_id,
            quantity: item.quantity,
            goods_spec_value_name: item.goods_spec_value_name,
            goods_spec_name: item.goods_spec_name,
            goods_value_name: item.goods_value_name,
            price: item.price,
            remark: item.remark,
          })),
        },
      ],
    });
  }
  uni.redirectTo({
    url: `/pages/success/success?totalPrice=${totalPrice.value}&type=store&id=${res.order_ids[0]}`,
  });
};
const selectMethod = (type) => {
  singleObj.value.userType = type;
};

const changePrice = (item) => {
  item.price = Number(item.price).toFixed(2);
  item.total_price = bc(`${item.price}*${item.quantity}`);
};

const toChooseUser = () => {
  uni.navigateTo({
    url: `/pagesShop/order/component/chooseUser?type=${singleObj.value.userType}`,
  });
};

const clearUser = () =>{
  Object.assign(singleObj.value, {
  c_user_id: undefined,
  c_user_name: "",
  current_address: {
    consignee: "请点击选择地址",
    address: "",
    mobile: "",
    id: undefined,
  },
  user_remark: "",
  detail: [cloneDeep(goodsObj.value)],
})
getGoodsListData(0);
}

const userShopId = ref("");

onUnload(() => {
  uni.$off("userInfo");
  uni.$off("useAddress");
});
onShow(() => {
  uni.$on("userInfo", (user) => {
    singleObj.value.c_user_id = user.id;
    singleObj.value.c_user_name = user.name;
    // 清空所有商品以及数据
    singleObj.value.detail.forEach((item, index) => {
      getGoodsListData(index);
    });
    getGoodsListData(0);
  });
  uni.$on("useAddress", (address) => {
    singleObj.value.current_address = address;
  });
});
onLoad(async () => {
  // 获取本人店铺id
  const res = await getUserInfo();
  userShopId.value = res.shop?.id;
  getGoodsListData(0);
});
</script>

<style scoped>
.order-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
}

/* 店铺信息样式 */
.store-info {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
}

.store-name {
  font-size: 32rpx;
  font-weight: 500;
}

/* 客户信息样式 */
.customer-info {
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin-top: 2rpx;
  border-bottom: 1px solid #eee;
}

.customer-row {
  display: flex;
  align-items: center;
}

.customer-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20rpx;
}

.avatar-img {
  width: 100%;
  height: 100%;
}

.customer-data {
  flex: 1;
}

.customer-name {
  font-size: 30rpx;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.customer-address {
  font-size: 26rpx;
  color: #666;
}

.address-arrow {
  width: 40rpx;
  text-align: right;
}

.arrow-icon {
  color: #ccc;
  font-size: 40rpx;
}

/* 商品列表样式 */
.product-list,
.added-product {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 0 30rpx;
}

.product-item,
.added-header {
  display: flex;
  align-items: center;
  padding: 25rpx 0;
}

.product-required {
  color: #f56c6c;
  font-size: 28rpx;
  margin-right: 5rpx;
}

.product-label,
.added-title {
  width: 100rpx;
  font-size: 28rpx;
  color: #333;
}

.product-value,
.added-value {
  flex: 1;
  font-size: 28rpx;
  color: #999;
}

.product-arrow {
  width: 40rpx;
  text-align: right;
}

/* 数量控制样式 */
.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-minus,
.quantity-plus {
  width: 60rpx;
  height: 60rpx;
  line-height: 56rpx;
  text-align: center;
  border: 1px solid #ddd;
  font-size: 36rpx;
  color: #333;
  background-color: #f7f7f7;
}

.quantity-input {
  width: 80rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  font-size: 28rpx;
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}

/* 备注输入框样式 */
.remark-input {
  flex: 1;
  font-size: 28rpx;
  height: 60rpx;
  border: none;
}

/* 价格信息样式 */
.price-info {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.price-label {
  font-size: 28rpx;
  color: #666;
}

.price-value {
  font-size: 28rpx;
  color: #f56c6c;
  margin-left: 20rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.total-price {
  margin-left: auto;
  font-size: 28rpx;
  color: #f56c6c;
}

/* 按钮样式 */
.action-buttons {
  display: flex;
  padding: 20rpx 0;
}

.add-button,
.delete-button {
  display: flex;
  align-items: center;
  height: 80rpx;
  padding: 0 30rpx;
  background-color: #eeeeee6b;
  border-radius: 4rpx;
  margin-right: 20rpx;
  gap: 10rpx;
}

.add-icon,
.delete-icon {
  font-size: 32rpx;
  margin-right: 8rpx;
}

.add-text,
.delete-text {
  font-size: 28rpx;
}

.delete-button {
  color: #f56c6c;
}

/* 底部结算栏样式 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100rpx;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #eee;
  z-index: 10;
}

.total-section {
  flex: 2;
  padding-left: 30rpx;
  font-size: 28rpx;
}

.total-amount {
  color: #f56c6c;
  font-weight: 500;
  font-size: 32rpx;
}

.tax-info {
  font-size: 24rpx;
  color: #999;
  margin-left: 8rpx;
}

.submit-button {
  flex: 1;
  height: 100%;
  background-color: #1989fa;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
}

.mgl-40 {
  margin-left: 40rpx;
}

.no-required {
  margin-left: 16rpx;
}

.method-tabs {
  display: flex;
  flex: 1;
}

.method-tab {
  flex: 1;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
  background-color: #f5f5f5;
}

.method-tab.active {
  background-color: #009fff;
  color: #fff;
}

.method-tab:first-child {
  border-top-left-radius: 4rpx;
  border-bottom-left-radius: 4rpx;
}

.method-tab:last-child {
  border-top-right-radius: 4rpx;
  border-bottom-right-radius: 4rpx;
}
.choose-user {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  font-family: "黑体", sans-serif;
  color: #666;
  justify-content: space-between;
  margin-bottom: 10rpx;
}
.choose-user-label {
  width: 168rpx;
}
.choose-input {
  width: 300rpx;
}
.choose-icon {
  width: 30rpx;
  height: 30rpx;
  object-fit: cover;
  padding: 10rpx;
}
.choose-user-name{
  background: #dad8d89e;
    padding: 10rpx;
    border-radius: 24rpx;
}
.choose-user-name-close{
  padding-left: 10rpx;
}
</style>
